﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public struct PosInfo
{
	public Vector3 position;
	public float scale;
}

/// <summary>
/// MacOS中，PlayerSetting - ColorSapce 必须等于 Gamma
/// Windows中，无所谓
/// </summary>
public class Test1 : MonoBehaviour 
{
	public ComputeShader shader;
	public GameObject prefab;

	private int count = 16;
	private ComputeBuffer buffer;
	private GameObject[] objects;

	void Start()
	{
		objects = new GameObject[count];
		for(int i=0;i<count;i++)
		{
			objects[i] = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity);
		}

		CreateBuffer();
	}

	void OnDisable()
	{
		ReleaseBuffer();
	}

	void CreateBuffer()
	{
		buffer = new ComputeBuffer(count, 4 * 3 + 4);
		PosInfo[] values = new PosInfo[count];

		for (int i = 0; i < count; i++) {
			PosInfo m = new PosInfo ();
			InitStruct (ref m, objects[i]);
			values [i] = m;
		}

		buffer.SetData (values);
	}

	void InitStruct(ref PosInfo m, GameObject obj)
	{
		m.scale = 1;
		m.position = obj.transform.position;
	}

	void Update()
	{
		//运行Shader
		Dispatch ();

		//根据Shader返回的buffer数据更新物体信息
		PosInfo[] values = new PosInfo[count];
		buffer.GetData(values);
		float scale = 1F;
		for (int i = 0; i < count; i++) {
			scale = values[i].scale;
			objects[i].transform.position = values[i].position;
			objects[i].transform.localScale = new Vector3(scale, scale, scale);
		}
	}

	void Dispatch()
	{
        int kernelId = shader.FindKernel("CSMain");
        //int kernelId = 0;

		shader.SetFloat("deltaTime", Time.deltaTime);
		shader.SetBuffer(kernelId, "buffer", buffer);
		shader.Dispatch(kernelId, 2, 2, 1);
	}

	void ReleaseBuffer()
	{
		buffer.Release();
	}

}
